/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.rsa.data;

import org.osgi.service.remoteserviceadmin.ExportReference;
import org.osgi.service.remoteserviceadmin.ExportRegistration;

/**
 * ExportRegistrationImpl : The {@link ExportRegistration} implementation
 * 
 * @author Romain DUBOIS
 */
public class ExportRegistrationImpl implements ExportRegistration {

    /** The export reference (if export suceeded) */
    private ExportReferenceImpl mReference;
    /** The export exception (if export failed) */
    private Throwable mException;

    // TODO : use java.util.concurrent.Future for lazy/asynchronuous
    // initialization?

    /**
     * Constructor for successfull exports.
     * 
     * @param pReference
     *            The export reference
     */
    ExportRegistrationImpl(final ExportReferenceImpl pReference) {
        super();
        mReference = pReference;
    }

    /**
     * Constructor for failed exports.
     * 
     * @param pException
     *            Tnhe export exception
     */
    public ExportRegistrationImpl(final Throwable pException) {
        super();
        mException = pException;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.service.remoteserviceadmin.ExportRegistration#getExportReference()
     */
    @Override
    public synchronized ExportReference getExportReference() {
        if (mException == null) {
            return mReference;
        }
        throw new IllegalStateException();
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.service.remoteserviceadmin.ExportRegistration#close()
     */
    @Override
    public synchronized void close() {
        if (mReference != null) {
            mReference.registrationClosed();
        }
        mReference = null;
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.osgi.service.remoteserviceadmin.ExportRegistration#getException()
     */
    @Override
    public Throwable getException() {
        return mException;
    }
}
